package com.wnxy.pms.product.core.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    // 交换机
    @Bean
    public TopicExchange orderExchange() {
        return new TopicExchange("order-exchange", true, false);
    }

    // 队列
    @Bean
    public Queue ttlOrderQueue() {
        Map params = new HashMap();
        params.put("x-message-ttl", 20000);
        params.put("x-dead-letter-exchange", "order-dead-letter-exchange");
        params.put("x-dead-letter-routing-key", "dead.letter.order");
        return new Queue("ttl-order-queue", true, false, false, params);
    }

    // 绑定
    @Bean
    public Binding bindTTLOrderQueue() {
        return BindingBuilder.bind(ttlOrderQueue()).to(orderExchange())
                .with("order.#");
    }

    // 死信交换机
    @Bean
    public TopicExchange orderDeadLetterExchange() {
        return new TopicExchange("order-dead-letter-exchange", true, false);
    }

    // 死信队列
    @Bean
    public Queue orderDeadLetterQueue() {
        return new Queue("order-dead-letter-queue", true, false, false);
    }

    // 死信绑定
    @Bean
    public Binding bindOrderDeadLetterQueue() {
        return BindingBuilder.bind(orderDeadLetterQueue())
                .to(orderDeadLetterExchange())
                .with("dead.letter.order");
    }

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory factory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(factory);
        rabbitAdmin.setAutoStartup(true);
        rabbitAdmin.declareExchange(orderExchange());
        rabbitAdmin.declareExchange(orderDeadLetterExchange());
        rabbitAdmin.declareQueue(ttlOrderQueue());
        rabbitAdmin.declareQueue(orderDeadLetterQueue());
        return rabbitAdmin;
    }

}
